package com.app.couponsharelife.ui.main.login

import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import com.google.gson.Gson
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.NewBindPhoneBean
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.manage.FinishActivityManager
import com.app.couponsharelife.ui.main.MainActivity
import com.app.couponsharelife.utils.AppUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_bindingphone.*
import okhttp3.MediaType
import okhttp3.RequestBody
import java.util.concurrent.TimeUnit

/**
 *Created by xct on 2019/1/3
 *Description:绑定手机号页面
 */
class BindingPhoneActivity:BaseActivity(),View.OnClickListener {
    private var disposable: Disposable? = null
    private var countDownNum: Int = 0
    private var userId=""
    private var userName=""
    private var unionId=""
    private var headPrice=""
    private var sex=""
    private var city=""
    private var province=""
    override val viewLayoutId: Int
        get() = R.layout.activity_bindingphone

    override fun initViews() {
        AppUtils.initImmersionBar(this,true)
        userId=intent.getStringExtra("UserId")?:""
        userName=intent.getStringExtra("UserName")?:""
        unionId=intent.getStringExtra("UnionId")?:""
        headPrice=intent.getStringExtra("HeadPrice")?:""
        sex=intent.getStringExtra("Sex")?:""
        city=intent.getStringExtra("City")?:""
        province=intent.getStringExtra("Province")?:""
        bindingphone_editphone.addTextChangedListener(object :TextWatcher{
            override fun afterTextChanged(s: Editable) {
                if (s.isNotEmpty()){
                    bindingphone_textlogin.setBackgroundResource(R.drawable.shape_red_ff0_ff4)
                }else{
                    bindingphone_textlogin.setBackgroundResource(R.drawable.shape_gray_cc20)
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }
        })
        bindingphone_llyzm.setOnClickListener(this)
        bindingphone_textlogin.setOnClickListener(this)
        bindingphone_llcolse.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.bindingphone_llyzm->{
                val phone=bindingphone_editphone.text.toString().trim()
                if (phone.isEmpty()) {
                    showToastMsg("请输入手机号")
                    return
                }
                if (phone.length<11) {
                    showToastMsg("请输入正确的手机号")
                    return
                }
                if (!AppUtils.isMobile(phone)) {
                    showToastMsg("请输入正确的手机号")
                    return
                }
                sendCode(phone)
                //sendCheckCodeSuccess()
            }
            R.id.bindingphone_textlogin->{
                val phone=bindingphone_editphone.text.toString().trim()
                val code=bindingphone_edityzm.text.toString().trim()
                if (phone.isEmpty()) {
                    showToastMsg("请输入手机号")
                    return
                }
                if (phone.length<11) {
                    showToastMsg("请输入正确的手机号")
                    return
                }
                if (!AppUtils.isMobile(phone)) {
                    showToastMsg("请输入正确的手机号")
                    return
                }
                if (code.isEmpty()) {
                    showToastMsg("请输入验证码")
                    return
                }
                if (code.length<4) {
                    showToastMsg("验证码不少于4位")
                    return
                }
                bindPhone(phone,code)
            }
            R.id.bindingphone_llcolse->{
                hideSoftInput(this)
                finish()
            }
        }
    }
    private fun sendCode(mobile:String){
        val map=HashMap<String,String>()
        map["mobile"]=mobile
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        //mViewMode?.freshSendCheckCode(map,true)
        RetrofitWorker.retrofitWorker.sendCheckCode(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<Any>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<Any>) {
                        if (it.code == 200) {
                            sendCheckCodeSuccess()
                        } else {
                            showToastMsg("发送失败")
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }
                    }

                })
    }
    private fun bindPhone(mobile:String,code:String){
        showProgressDialog("请稍后...")
        val map=HashMap<String,String>()
        map["mobile"]=mobile
        map["code"]=code
        map["nickName"]=userName
        map["headPic"]=headPrice
        map["openId"]=userId
        map["unionId"]=unionId
        map["sex"]=sex
        map["country"]=""
        map["province"]=province
        map["city"]=city
        map["area"]=""
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        //loginViewMode?.freshBindPhone(map,true)
        RetrofitWorker.retrofitWorker.bindPhone(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<NewBindPhoneBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<NewBindPhoneBean>) {
                        dismissProgressDialog()
                        if (it.code == 200 && it.data!= null) {
                            showToastMsg("登录成功")
                            AppUtils.setString(Contacts.USER_MOBILE, it.data!!.mobile!!)
                            AppUtils.setString(Contacts.USERID, it.data!!.id!!)
                            AppUtils.setString(Contacts.ADZONE_ID, it.data!!.relation_id?:"")
                            AppUtils.setString(Contacts.USER_GRADE_ID, it.data!!.sellerlevel.toString())
                            AppUtils.setString(Contacts.COMMISSION_RATIO, it.data!!.commissionRatio?:"")
                            FinishActivityManager.getInstance().finishAllActivity()
                            startActivity(Intent(this@BindingPhoneActivity, MainActivity::class.java))
                        } else {
                            showToastMsg("请求失败")
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }
                    }

                })
    }
    private fun sendCheckCodeSuccess() {
        countDownNum = 59
        bindingphone_llyzm.isClickable = false
        bindingphone_texthqyzm.setTextColor(resources.getColor(R.color.gray_cc))
        disposable = Observable.interval(0, 1, TimeUnit.SECONDS)//10s 倒计时
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ _ ->
                    if (countDownNum < 0)
                        goAhead()
                    else {
                        bindingphone_texthqyzm.text = "${countDownNum}s后重发"
                        countDownNum--
                    }
                }) { goAhead() }
    }

    private fun goAhead() {
        bindingphone_llyzm.isClickable = true
        bindingphone_texthqyzm.text="获取验证码"
        bindingphone_texthqyzm.setTextColor(resources.getColor(R.color.black))
        disposable?.dispose()
        disposable == null
    }

    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
}